package com.yonyou.gmmc.dealerApp.api.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.constants.RoleConstant;
import org.marketing.common.dto.user.AccessTokenDto;
import org.marketing.common.dto.user.LoginUserDto;
import org.marketing.common.dto.user.RoleDto;
import org.marketing.common.dto.user.TM_UsersDto;
import org.marketing.common.exception.ServiceAppException;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.dealerApp.api.dao.TmUsersMapper;
import com.yonyou.gmmc.dealerApp.api.entity.MD5Encrypt;

/**
 * @author kaihua 由于其他提供服务的微服务接口文档不完整，为了赶进度，目前所有实现放在本微服务自身中实现。
 *         后续有时间整理各个提供服务的微服务开放的功能接口之后，再通过调用其他微服务功能的方式调用功能
 *
 */
@Service
@Transactional
public class DealerAppLoginService {
	private Logger logger = Logger.getLogger(DealerAppLoginService.class);
	
	@Autowired
	private TmUsersMapper usersDao;
	
	@Autowired
    private OAuthService oAuthService;

	public Map<String,Object> dealerAppUserLogin(LoginUserDto loginUserDto) throws Exception {
        List<LoginUserDto> dtos = dealerAppUserLoginForSer(loginUserDto);
        Map<String,Object> result = new HashMap<String,Object>();
        if(CheckUtil.NullOrEmpty(dtos)){
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.ERR_MSG, "输入的用户名或密码错误，请重新登录！本次支持的角色是销售顾问或者售后顾问登录。");
        } else {
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
            result.put(ResultMsgConstants.ERR_MSG, "");
        }
        result.put("dealerUsers", dtos);
        result.put("userCount", dtos.size());
        
        return result;
    }
	private List<LoginUserDto> dealerAppUserLoginForSer(LoginUserDto loginUserDto) {
		try {
            loginUserDto.setPassWord(MD5Encrypt.MD5Encode(loginUserDto.getPassWord()));
            
            List<LoginUserDto> dtoList = usersDao.getUserByPhoneAndPassWord(loginUserDto);
            List<LoginUserDto> returnResult = new ArrayList<LoginUserDto>();
            Map<String,List<RoleDto>> roleMap = new HashMap<String,List<RoleDto>>();
            for(LoginUserDto temp : dtoList) {
            	roleMap.put(temp.getUserId().toString(), new ArrayList<RoleDto>());
            }
            
            for(LoginUserDto temp : dtoList) {
            	List<RoleDto> roleList = roleMap.get(temp.getUserId().toString());
            	RoleDto role = new RoleDto();
            	role.setRoleId(Integer.valueOf(temp.getPosition()));
            	roleList.add(role);
            }
            for(LoginUserDto temp : dtoList) {
            	List<RoleDto> roleList = roleMap.get(temp.getUserId().toString());
            	temp.setRoleList(roleList);
            }
            logger.debug("整理之后的权限用户关系："+dtoList);
            // 设定每个用户的主页信息
            if (!CheckUtil.NullOrEmpty(dtoList)){
                for (int i= 0; i<dtoList.size();i++){
                    LoginUserDto user = dtoList.get(i);
                    if (CheckUtil.NullOrEmpty(user.getRoleList())){
                        dtoList.remove(user);
                        i--;
                    } else {
                        boolean afterseles = false;
                        boolean seles = false;
                        List<RoleDto> roleList = user.getRoleList();
                        for (RoleDto ro :roleList){
                            if (RoleConstant.AFTER_SALES_CONSULTANT_ID.intValue() == ro.getRoleId().intValue()){
                                afterseles = true;
                            }
                            if (RoleConstant.SALES_CONSULTANT_ID.intValue() == ro.getRoleId().intValue()){
                                seles = true;
                            }
                            
                        }
                        
                        if (afterseles && seles){
                            user.setRoleType("3");
                        } else if (afterseles) {
                            user.setRoleType("2");
                        } else if (seles){
                            user.setRoleType("1");
                        }
                        /*
                        // 每个人员的主页信息
                        List<Map<String,Object>> homePageInfo = getHomePageInfo(user.getDealerCode(),user.getUserId().intValue(),user.getRoleType());
                        user.setHomePageInfo(homePageInfo);*/
                        returnResult.add(user);
                    }
                }
            }
            
            return returnResult;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }
	}

	public Map<String, Object> selectDealer(LoginUserDto loginUserDto)throws ServiceAppException,
    ServiceBizException{
        Map<String, Object> result = new HashMap<String, Object>();
        result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.ERR_MSG, "");
        try {
                AccessTokenDto accessToken = dealerAppUserChangeDealer(loginUserDto);
                result.put("accessToken",accessToken);
        } catch (Exception e) {
            this.logger.info("dealerAppUserChangeDealer获取TOKEN错误：",e);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.ERR_MSG, "获取TOKEN出错-"+e.getMessage());
        }
        return result;
    }
	private AccessTokenDto dealerAppUserChangeDealer(LoginUserDto loginUserDto)throws ServiceAppException, ServiceBizException{
        
        loginUserDto.setPassWord(MD5Encrypt.MD5Encode(loginUserDto.getPassWord()));
        
        List<LoginUserDto> dtoList = usersDao.getUserByPhoneAndPassWord(loginUserDto);
        if (null != dtoList && !dtoList.isEmpty()){
            LoginUserDto loginUser = dtoList.get(0);
            TM_UsersDto user = new TM_UsersDto();
            user.setUserId(loginUser.getUserId());
            AccessTokenDto accessToken = oAuthService.refreshAccessToken(user);
            return accessToken;
        }
        
        return null;
    }
	
}
